package cz.proks.easyhelpdesk.gae.api.impl.db;

import java.util.LinkedList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.transaction.annotation.Transactional;

import cz.proks.easyhelpdesk.api.BaseHelpdeskApi;
import cz.proks.easyhelpdesk.api.exception.ApiException;
import cz.proks.easyhelpdesk.api.model.base.AnIdentifiableHelpdeskModel;
import cz.proks.easyhelpdesk.gae.api.impl.dbo.base.ConvertibleDbo;

public abstract class BaseHelpdeskApiImpl<Entity extends AnIdentifiableHelpdeskModel> extends BaseApiImpl<Entity> implements BaseHelpdeskApi<Entity> {    
    private final Logger log = LoggerFactory.getLogger(getClass());
    
    @Override
    protected abstract Class<Entity> getDomainClass();

    @Override
    protected abstract Entity getDboObject(Entity entity);
    
    @Override
    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    public List<Entity> listForHelpdesk(Long helpdeskId) throws ApiException {
        log.debug("list():: Start with helpdeskId '{}'", helpdeskId);
                    
        List<Entity> entities = new LinkedList<Entity>();
        List<ConvertibleDbo<Entity>> dboEntities = null;
        
        try { dboEntities =  getEntityManager().createQuery("FROM " + getDboClass().getName() + " WHERE helpdesk_id = :helpdeskId")
                                .setParameter("helpdeskId", helpdeskId)
                                .getResultList();
        } catch (EmptyResultDataAccessException erdae) {
            // NOP
        } catch (Exception e) {
            throw new ApiException(e);
        }

        entities = dboEntities == null ? entities : fromDboList(dboEntities); 
        log.debug("list():: End with {}", (entities == null ? "null list" : "list of " + entities.size() + " elements"));
        return entities;
    }
}
